#include "QFrameDirsBrowser.h"
#include "ui_QFrameDirsBrowser.h"
#include <QDir>
#include <QFileInfo>
#include <QMessageBox>
#include <QDateTime>
#include <QDebug>
QFrameDirsBrowser::QFrameDirsBrowser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QFrameDirsBrowser),
    historyIndex(-1)
{
    ui->setupUi(this);
    // 创建文件系统模型
    fileSystemModel = new QFileSystemModel(this);
    fileSystemModel->setRootPath(QDir::rootPath());
    fileSystemModel->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
    fileSystemModel->setNameFilterDisables(false);

    // 创建代理模型用于排序
    proxyModel = new QSortFilterProxyModel(this);
    proxyModel->setSourceModel(fileSystemModel);
    proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);

    // 创建视图
    treeView = new QTreeView(this);
    treeView->setModel(proxyModel);
    treeView->setRootIndex(proxyModel->mapFromSource(fileSystemModel->index(QDir::homePath())));
    treeView->setSortingEnabled(true);
    treeView->sortByColumn(0, Qt::AscendingOrder);
    treeView->hideColumn(1); // 隐藏大小列
    treeView->hideColumn(3); // 隐藏权限列

    listView = new QListView(this);
    listView->setModel(proxyModel);
    listView->setRootIndex(proxyModel->mapFromSource(fileSystemModel->index(QDir::homePath())));
    listView->setViewMode(QListView::ListMode);
    listView->setHidden(true); // 默认隐藏列表视图

    // 连接视图信号
    connect(treeView, &QTreeView::clicked, this, &QFrameDirsBrowser::onCurrentIndexChanged);
    connect(listView, &QListView::clicked, this, &QFrameDirsBrowser::onCurrentIndexChanged);

    // 创建导航控件
    pathEdit = new QLineEdit(this);
    pathEdit->setText(QDir::homePath());

    goButton = new QPushButton("转到", this);
    backButton = new QPushButton("后退", this);
    forwardButton = new QPushButton("前进", this);
    upButton = new QPushButton("向上", this);

    viewModeCombo = new QComboBox(this);
    viewModeCombo->addItem("树形视图");
    viewModeCombo->addItem("列表视图");
    viewModeCombo->addItem("图标视图");

    // 创建状态栏
    statusLabel = new QLabel(this);

    // 连接信号和槽
    connect(pathEdit, &QLineEdit::returnPressed, this, &QFrameDirsBrowser::onGoClicked);
    connect(goButton, &QPushButton::clicked, this, &QFrameDirsBrowser::onGoClicked);
    connect(backButton, &QPushButton::clicked, this, &QFrameDirsBrowser::onBackClicked);
    connect(forwardButton, &QPushButton::clicked, this, &QFrameDirsBrowser::onForwardClicked);
    connect(upButton, &QPushButton::clicked, this, &QFrameDirsBrowser::onUpClicked);
    connect(viewModeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &QFrameDirsBrowser::onViewModeChanged);

    // 创建布局
    QHBoxLayout *navLayout = new QHBoxLayout();
    navLayout->addWidget(backButton);
    navLayout->addWidget(forwardButton);
    navLayout->addWidget(upButton);
    navLayout->addWidget(pathEdit);
    navLayout->addWidget(goButton);
    navLayout->addWidget(viewModeCombo);

    QVBoxLayout *mainLayout = new QVBoxLayout();
    mainLayout->addLayout(navLayout);
    mainLayout->addWidget(treeView);
    mainLayout->addWidget(listView);
    mainLayout->addWidget(statusLabel);

    setLayout(mainLayout);

    // 初始化历史记录
    navigationHistory.append(QDir::homePath());
    historyIndex = 0;

    updateStatusBar();
}

QFrameDirsBrowser::~QFrameDirsBrowser()
{
    delete fileSystemModel;
    delete proxyModel;
    delete ui;
}


void QFrameDirsBrowser::onPathChanged(const QString &path)
{
    QDir dir(path);
    if (!dir.exists()) {
        //QMessageBox::warning(this, "错误", "目录不存在!");
        return;
    }
    work_path = path; //缓存工作目录
    pathEdit->setText(path);

    QModelIndex index = fileSystemModel->index(path);
    treeView->setRootIndex(proxyModel->mapFromSource(index));
    listView->setRootIndex(proxyModel->mapFromSource(index));

    // 更新历史记录
    if (historyIndex < navigationHistory.size() - 1) {
        navigationHistory = navigationHistory.mid(0, historyIndex + 1);
    }
    navigationHistory.append(path);
    historyIndex++;

    updateStatusBar();
}
void QFrameDirsBrowser::findFiles(const QString &currentDir, const QString type, QFileInfoList &result)
{
    QDir dir(currentDir);
    // 配置过滤器：只处理文件和目录，排除.和..
    QDir::Filters filters = QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot;

    // 获取当前目录下的所有条目
    QFileInfoList entries = dir.entryInfoList(filters);

    foreach (const QFileInfo &entry, entries) {
        if (entry.isDir()) {
            // 如果是目录，递归查找
            findFiles(entry.filePath(),type,result);
        } else if (entry.isFile()) {
            // 检查文件扩展名是否为.bit（不区分大小写）
            if (entry.suffix().compare(type, Qt::CaseInsensitive) == 0) {
                result.append(entry);
            }
        }
    }
}
QStringList QFrameDirsBrowser::getAllFilePath(QString type,int max_level)
{
    //获取工作目录
    QDir baseDir(work_path);

    //输出目录格式
    QStringList file_list;
    QFileInfoList typeFiles;
    findFiles(work_path,type,typeFiles);
    //按照 文件名 + 大小 + 5级路径的格式进行输出
    for (int i = 0; i < typeFiles.size(); ++i) {
        const QFileInfo &fileInfo = typeFiles[i]; //获取文件信息

        file_list.append(fileInfo.baseName()); //加载基础名
        QString hex = QString("%1").arg(fileInfo.size(), 8, 16, QChar('0')).toUpper(); // 8位，大写，不足补0
        file_list.append(hex); //加载大小

        QString rel_path = baseDir.relativeFilePath(fileInfo.path()); //计算相对路径

        QStringList addrs = rel_path.split("/"); //拆分相对路径
        if(addrs.size() > max_level) //不允许大于最大深度
        {
            QDEBUG << rel_path << "size is not match";
            break;
        }
        for(int j = 0; j < max_level; j++)
        {
            if(j < addrs.size())
            {
                file_list.append(addrs.at(addrs.size()-1-j));
            }
            else
            {
                file_list.append("00000000"); //多于的目录填充全0值
            }
        }
    }

    return file_list;
}


void QFrameDirsBrowser::onGoClicked()
{
    onPathChanged(pathEdit->text());
}

void QFrameDirsBrowser::onBackClicked()
{
    if (historyIndex > 0) {
        historyIndex--;
        QString path = navigationHistory[historyIndex];
        pathEdit->setText(path);

        QModelIndex index = fileSystemModel->index(path);
        treeView->setRootIndex(proxyModel->mapFromSource(index));
        listView->setRootIndex(proxyModel->mapFromSource(index));

        updateStatusBar();
    }
}

void QFrameDirsBrowser::onForwardClicked()
{
    if (historyIndex < navigationHistory.size() - 1) {
        historyIndex++;
        QString path = navigationHistory[historyIndex];
        pathEdit->setText(path);

        QModelIndex index = fileSystemModel->index(path);
        treeView->setRootIndex(proxyModel->mapFromSource(index));
        listView->setRootIndex(proxyModel->mapFromSource(index));

        updateStatusBar();
    }
}

void QFrameDirsBrowser::onUpClicked()
{
    QDir currentDir(pathEdit->text());
    if (currentDir.cdUp()) {
        onPathChanged(currentDir.path());
    }
}

void QFrameDirsBrowser::onViewModeChanged(int index)
{
    switch (index) {
        case 0: // 树形视图
            treeView->setHidden(false);
            listView->setHidden(true);
            break;
        case 1: // 列表视图
            treeView->setHidden(true);
            listView->setHidden(false);
            listView->setViewMode(QListView::ListMode);
            break;
        case 2: // 图标视图
            treeView->setHidden(true);
            listView->setHidden(false);
            listView->setViewMode(QListView::IconMode);
            listView->setIconSize(QSize(64, 64));
            listView->setGridSize(QSize(80, 100));
            break;
    }
}

void QFrameDirsBrowser::onCurrentIndexChanged(const QModelIndex &index)
{
    QModelIndex sourceIndex = proxyModel->mapToSource(index);
    QString path = fileSystemModel->filePath(sourceIndex);

    if (fileSystemModel->isDir(sourceIndex)) {
        onPathChanged(path);
    } else {
        // 如果是文件，更新状态栏显示文件信息
        QFileInfo fileInfo(path);
        statusLabel->setText(QString("文件: %1, 大小: %2 bytes, 修改时间: %3")
            .arg(fileInfo.fileName())
            .arg(fileInfo.size())
            .arg(fileInfo.lastModified().toString("yyyy-MM-dd hh:mm:ss")));
    }
}

void QFrameDirsBrowser::updateStatusBar()
{
    QDir dir(pathEdit->text());
    QFileInfoList entries = dir.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);

    int fileCount = 0;
    int dirCount = 0;
    qint64 totalSize = 0;

    for (const QFileInfo &info : entries) {
        if (info.isFile()) {
            fileCount++;
            totalSize += info.size();
        } else if (info.isDir()) {
            dirCount++;
        }
    }

    statusLabel->setText(QString("目录: %1, 文件: %2, 总大小: %3 bytes")
        .arg(dirCount)
        .arg(fileCount)
        .arg(totalSize));
}

